<template>
  <div class="map-container">
    <div id="map" class="map"></div>
    
    <!-- 图层控制面板 -->
    <div class="layer-control">
      <h3>图层控制</h3>
      
      <!-- 底图切换 -->
      <div class="layer-group">
        <div class="group-title">底图</div>
        <div class="layer-item">
          <el-radio-group v-model="currentBaseMap" @change="switchBaseMap">
            <el-radio label="gaode">高德地图</el-radio>
            <el-radio label="tdtVec">天地图矢量</el-radio>
            <el-radio label="tdtImg">天地图影像</el-radio>
          </el-radio-group>
        </div>
      </div>

      <!-- 业务图层 -->
      <div class="layer-group">
        <div class="group-title">业务图层</div>
        <div class="layer-item" v-for="layer in businessLayers" :key="layer.id">
          <el-checkbox 
            v-model="layer.visible" 
            @change="toggleLayer(layer)">
            {{ layer.name }}
          </el-checkbox>
          <el-slider 
            v-if="layer.visible"
            v-model="layer.opacity" 
            :min="0"
            :max="1"
            :step="0.1"
            @change="(val) => updateOpacity(layer, val)"
            class="opacity-slider">
          </el-slider>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import 'leaflet/dist/leaflet.css';
import L from 'leaflet';

export default {
  name: 'LayerDemo',
  
  data() {
    return {
      map: null,
      currentBaseMap: 'gaode',
      baseLayers: {},
      businessLayers: [
        {
          id: 'supermapChina',
          name: 'SuperMap中国',
          visible: false,
          opacity: 1,
          layer: null,
          url: 'http://support.supermap.com.cn:8090/iserver/services/map-china400/wms111/China',
          // url: 'https://iserver.supermap.io/iserver/services/map-china400/wmts100',
          
          options: {
            layers: 'China',
            format: 'image/png',
            transparent: true,
            version: '1.1.1',
            // version: '1.0.0',
            attribution: '© SuperMap'
          }
        },
        {
          id: 'arcgisWorldImagery',
          name: 'ArcGIS卫星影像',
          visible: false,
          opacity: 1,
          layer: null,
          url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
          options: {
            attribution: 'Source: Esri, Maxar, Earthstar Geographics, and the GIS User Community',
            minZoom: 0,
            maxZoom: 19,
            tileSize: 256,
          }
        },
        {
          id: 'wmts',
          name: 'WMTS图层',
          visible: false,
          opacity: 1,
          layer: null,
          url: 'https://t{s}.tianditu.gov.cn/vec_w/wmts',
          options: {
            subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
            layer: 'vec',
            style: 'default',
            tilematrixSet: 'w',
            format: 'tiles',
            transparent: true,
            tk: '8c88eba266a165eac9c085724708f2f9',
            attribution: '天地图'
          }
        },
        {
          id: 'xyz',
          name: 'XYZ图层',
          visible: false,
          opacity: 1,
          layer: null,
          url: 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png',
          options: {
            subdomains: ['a', 'b', 'c'],
            attribution: '© OpenStreetMap contributors, © CARTO'
          }
        }
      ]
    };
  },

  mounted() {
    this.initMap();
  },

  methods: {
    initMap() {
      // 初始化地图
      this.map = L.map('map', {
        center: [39.90923, 116.397428],
        zoom: 12,
        zoomControl: false,
        crs : L.CRS.EPSG3857
      });

      // 初始化底图
      this.baseLayers = {
        gaode: L.tileLayer('https://webst0{s}.is.autonavi.com/appmaptile?style=7&x={x}&y={y}&z={z}', {
          subdomains: ['1', '2', '3', '4'],
          attribution: '高德地图'
        }),
        tdtVec: L.tileLayer('https://t{s}.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=8c88eba266a165eac9c085724708f2f9', {
          subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
          attribution: '天地图'
        }),
        tdtImg: L.tileLayer('https://t{s}.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=8c88eba266a165eac9c085724708f2f9', {
          subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
          attribution: '天地图'
        })
      };

      // 添加默认底图
      this.baseLayers[this.currentBaseMap].addTo(this.map);

      // 添加天地图注记层
      const tdtVecLabel = L.tileLayer('https://t{s}.tianditu.gov.cn/cva_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=8c88eba266a165eac9c085724708f2f9', {
        subdomains: ['0', '1', '2', '3', '4', '5', '6', '7']
      });

      const tdtImgLabel = L.tileLayer('https://t{s}.tianditu.gov.cn/cia_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=8c88eba266a165eac9c085724708f2f9', {
        subdomains: ['0', '1', '2', '3', '4', '5', '6', '7']
      });

      // 监听底图切换，同步切换注记层
      this.$watch('currentBaseMap', (newVal) => {
        // 移除所有注记层
        this.map.removeLayer(tdtVecLabel);
        this.map.removeLayer(tdtImgLabel);
        
        // 根据当前底图添加对应的注记层
        if (newVal === 'tdtVec') {
          tdtVecLabel.addTo(this.map);
        } else if (newVal === 'tdtImg') {
          tdtImgLabel.addTo(this.map);
        }
      });

      // 初始化业务图层
      this.initBusinessLayers();

      // 添加缩放控件
      L.control.zoom({
        position: 'bottomright'
      }).addTo(this.map);
    },

    initBusinessLayers() {
      this.businessLayers.forEach(layerConfig => {
        switch (layerConfig.id) {
          case 'supermapChina':
            layerConfig.layer = L.tileLayer.wms(layerConfig.url, {
              layers: layerConfig.options.layers,
              format: layerConfig.options.format,
              transparent: layerConfig.options.transparent,
              version: layerConfig.options.version,
              attribution: layerConfig.options.attribution
            });
            break;
          case 'arcgisWorldImagery':
            layerConfig.layer = L.tileLayer(layerConfig.url, {
              attribution: layerConfig.options.attribution,
              minZoom: layerConfig.options.minZoom,
              maxZoom: layerConfig.options.maxZoom,
              tileSize: layerConfig.options.tileSize,
            });
            break;
          case 'wmts':
            layerConfig.layer = L.tileLayer(
              `${layerConfig.url}?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=${layerConfig.options.layer}&STYLE=${layerConfig.options.style}&TILEMATRIXSET=${layerConfig.options.tilematrixSet}&FORMAT=${layerConfig.options.format}&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=${layerConfig.options.tk}`,
              {
                subdomains: layerConfig.options.subdomains,
                attribution: layerConfig.options.attribution
              }
            );
            break;
          case 'xyz':
            layerConfig.layer = L.tileLayer(layerConfig.url, layerConfig.options);
            break;
        }
      });
    },

    switchBaseMap(type) {
      // 移除当前底图
      Object.values(this.baseLayers).forEach(layer => {
        this.map.removeLayer(layer);
      });
      // 添加新底图
      this.baseLayers[type].addTo(this.map);
    },

    toggleLayer(layer) {
      if (layer.visible) {
        layer.layer.addTo(this.map);
      } else {
        this.map.removeLayer(layer.layer);
      }
    },

    updateOpacity(layer, value) {
      if (layer.layer) {
        layer.layer.setOpacity(value);
      }
    }
  },

  beforeDestroy() {
    if (this.map) {
      this.map.remove();
    }
  }
};
</script>

<style lang="scss" scoped>
.map-container {
  width: 100%;
  height: 100vh;
  position: relative;
}

.map {
  width: 100%;
  height: 100%;
}

.layer-control {
  position: absolute;
  top: 10px;
  right: 10px;
  background: white;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.15);
  z-index: 1000;
  min-width: 250px;
  max-height: calc(100vh - 40px);
  overflow-y: auto;

  h3 {
    margin: 0 0 15px 0;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;
    color: #303133;
    font-size: 16px;
  }
}

.layer-group {
  margin-bottom: 15px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;

  &:last-child {
    margin-bottom: 0;
  }
}

.group-title {
  font-weight: bold;
  color: #606266;
  margin-bottom: 10px;
  font-size: 14px;
}

.layer-item {
  margin: 8px 0;
  
  .el-checkbox {
    display: block;
    margin-bottom: 5px;
  }
}

.opacity-slider {
  margin-top: 5px;
  padding: 0 10px;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .layer-control {
    left: 10px;
    right: 10px;
    max-height: 50vh;
  }
}
</style> 